//
//  PersonalMessageViewController.m
//  QuanZiChat
//
//  Created by lanou3g on 15/11/27.
//  Copyright © 2015年 ZhongHongLin. All rights reserved.
//

#import "PersonalMessageViewController.h"
#import "ChangeMessageViewController.h"
#import "QRCodeViewController.h"
@interface PersonalMessageViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;//头像
@property (weak, nonatomic) IBOutlet UIView *headView;//分区头视图
@property (weak, nonatomic) IBOutlet UITableView *tableView;


@end

@implementation PersonalMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //改变声明周期
    [self.headImageView layoutIfNeeded];
    
    //设置头像为圆形
    [self.headImageView.layer setCornerRadius:self.headImageView.frame.size.width/2.0];
    
    [self addGestureRecognizer];
    

//-----------------------------------------------//
    AVFile *file = [[AVUser currentUser] objectForKey:@"headImage"];
    
    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        
        self.headImageView.image = [UIImage imageWithData:data];
        self.headImageView.clipsToBounds = YES;
        
    } progressBlock:^(NSInteger percentDone) {
        
        NSLog(@"%ld", percentDone);
    }];
//-----------------------------------------------//
 
    // Do any additional setup after loading the view.
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //改变声明周期
    [self.headImageView layoutIfNeeded];
    
    //设置头像为圆形
    [self.headImageView.layer setCornerRadius:self.headImageView.frame.size.width/2.0];
    
    self.headImageView.clipsToBounds = YES;
    
    [self.tableView reloadData];
}

//返回上一个界面
- (IBAction)reurnLastController:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//添加手势
-(void)addGestureRecognizer{
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    
    //手势添加到视图
    [self.headImageView addGestureRecognizer:tapGesture];
    self.headImageView.userInteractionEnabled = YES;
}

-(void)tapGestureAction:(UITapGestureRecognizer *)tapGesture{
    
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
    
    pickerVC.delegate = self;
    
    pickerVC.allowsEditing = YES;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择图片来源" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"从手机图库获取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:pickerVC animated:YES completion:nil];
        
    }];
    
    UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"从手机相机获取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:pickerVC animated:YES completion:nil];
        
    }];
    
    [alertController addAction:alertAction1];
    [alertController addAction:alertAction2];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
   
    self.headImageView.image = image;
    
    self.headImageView.contentMode = UIViewContentModeScaleToFill;
    
    self.headImageView.clipsToBounds = YES;
    
    //获取当前用户
    AVUser *currentUser = [AVUser currentUser];
    
    //将图片转成data
    NSData *imageData = UIImagePNGRepresentation(image);
    
    //获取data存成file
    AVFile *imageFile = [AVFile fileWithName:@"image.png" data:imageData];
    
    //上传文件
    [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            NSLog(@"成功");
        }else{
            NSLog(@"%@",error);
        }
        
    } progressBlock:^(NSInteger percentDone) {
        
        NSLog(@"%ld",percentDone);
    }];
    
    //将图片添加到user表中
    [currentUser setObject:imageFile forKey:@"headImage"];
    //后台保存数据
    [currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
       
        if (succeeded) {
            NSLog(@"插入成功");
        }else{
            NSLog(@"%@",error);
        }
    }];
    
    
    

    [self dismissViewControllerAnimated:YES completion:nil];
    
}




#pragma mark - tableView Delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 7;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AVUser *currentUser = [AVUser currentUser];
    if (indexPath.row == 0) {
        UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
        
        cell1.textLabel.text = @"昵称";
        cell1.detailTextLabel.text = [currentUser objectForKey:@"nickName"];
        return cell1;
    }
    if (indexPath.row == 1) {
        UITableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        cell2.textLabel.text = @"找我玩号";
        cell2.detailTextLabel.text = currentUser.username;
        return cell2;
    }
    if (indexPath.row == 2) {
        UITableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        cell3.textLabel.text = @"二维码";
        UIImageView *qrCode = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width - 60, 5, 50, 50)];

        cell3.detailTextLabel.text = @"";
        AVFile *file = [[AVUser currentUser] objectForKey:@"QRCodeImage"];
        
        
        [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
            
            qrCode.image = [UIImage imageWithData:data];
            
            
        } progressBlock:^(NSInteger percentDone) {
            
            NSLog(@"%ld", percentDone);
        }];

        
        
        cell3.accessoryView = qrCode;

        
        return cell3;
    }
    if (indexPath.row == 3) {
        UITableViewCell *cell4 = [tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
        cell4.textLabel.text = @"性别";
        return cell4;
    }
    if (indexPath.row == 4) {
        UITableViewCell *cell5 = [tableView dequeueReusableCellWithIdentifier:@"cell5" forIndexPath:indexPath];
        cell5.textLabel.text = @"生日";
        cell5.detailTextLabel.text = [currentUser objectForKey:@"birthday"];
            return cell5;
    }
    if (indexPath.row == 5) {
        UITableViewCell *cell6 = [tableView dequeueReusableCellWithIdentifier:@"cell6" forIndexPath:indexPath];
        cell6.textLabel.text = @"地区";
        return cell6;
    }
    if (indexPath.row == 6) {
        UITableViewCell *cell7 = [tableView dequeueReusableCellWithIdentifier:@"cell7" forIndexPath:indexPath];
        cell7.textLabel.text = @"个性签名";
        cell7.detailTextLabel.text = [currentUser objectForKey:@"IndividualitySignature"];
        
        return cell7;
    }
    return nil;
    
}

//点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ChangeMessageViewController *changeMessageVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ChangeMessageViewController"];
    
    AVUser *currentUser = [AVUser currentUser];
    
    if (indexPath.row == 0) {
        changeMessageVC.number = 0;
        changeMessageVC.navigationItem.title = @"修改昵称";
        [self showViewController:changeMessageVC sender:nil];
        
    }
    if (indexPath.row == 1) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您的账号" message:@"用于区别用户身份的唯一标识" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:alertAction];
        [self showViewController:alertController sender:nil];
    }
    if (indexPath.row == 2) {
        
        QRCodeViewController *qrCodeVC = [self.storyboard instantiateViewControllerWithIdentifier:@"QRCodeViewController"];
        
        [self showViewController:qrCodeVC sender:nil];
    }
    if (indexPath.row ==  4) {
        NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n":@"\n\n\n\n\n\n\n\n\n";
        UIDatePicker *datePicker = [[UIDatePicker alloc]init];
        datePicker.maximumDate = [NSDate date];
        datePicker.datePickerMode = UIDatePickerModeDate;
        UIAlertController *alterController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction *actionA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy年MM月dd日";
            NSString *dateStr = [formatter stringFromDate:datePicker.date];
            cell.detailTextLabel.text = dateStr;
            //_curUser.birthday = datePicker.date;
            //[_curUser saveInBackground];
            [currentUser setObject:dateStr forKey:@"birthday"];
            [currentUser saveInBackground];
            
        }];
        [alterController.view addSubview:datePicker];
        UIAlertAction *actionB = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alterController addAction:actionA];
        [alterController addAction:actionB];
        [self presentViewController:alterController animated:YES completion:nil];
    }
    if (indexPath.row == 6) {
        
        changeMessageVC.number = 6;
        [self showViewController:changeMessageVC sender:nil];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
